package modules

import (
	"errors"
	"gorm.io/gorm"
)

func (A *AssetInventory) AssetAdd() bool {
	if err := DB.Where(&AssetInventory{User: A.User, Address: A.Address}).First(&A).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			DB.Create(&A)
			return true
		}
	}
	return false
}

func (A *AssetInventory) AssetDelete() bool {
	err := DB.Where("user = ? AND address = ?", A.User, A.Address).Unscoped().Delete(&A).Error
	if err != nil {
		return false
	}
	return true
}

func (A *AssetInventory) AssetUpdate() bool {
	host := AssetInventory{}
	DB.Where("ID = ?",A.ID).First(&host)
	host.User = A.User
	host.Address = A.Address
	err := DB.Save(&host).Error
	if err != nil{
		return false
	} else {
		return true
	}
}
func (A *AssetInventory) AssetGet() ([]AssetInventory,error) {
	var Inventory []AssetInventory
	err := DB.Find(&Inventory).Error
	if err != nil {
		return nil,err
	}
	return Inventory,nil
}

func (S *ServiceInventory) ServiceAdd() bool {
	if err := DB.Where(&ServiceInventory{User: S.User, Address: S.Address}).First(&S).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			DB.Create(&S)
			return true
		}
	}
	return false
}

func (S *ServiceInventory) ServiceDelete() bool {
	err := DB.Where("user = ? AND address = ?", S.User, S.Address).Unscoped().Delete(&S).Error
	if err != nil {
		return false
	}
	return true
}

func (S *ServiceInventory) ServiceUpdate() bool {
	host := ServiceInventory{}
	DB.Where("ID = ?",S.ID).First(&host)
	host.User = S.User
	host.Address = S.Address
	err := DB.Save(&host).Error
	if err != nil{
		return false
	} else {
		return true
	}
}

func (A *ServiceInventory) ServiceGet() ([]ServiceInventory,error) {
	var Inventory []ServiceInventory
	err := DB.Find(&Inventory).Error
	if err != nil {
		return nil,err
	}
	return Inventory,nil
}